<template>
  <div>
    <ylheader :leftsvg="true" :title="'收藏'" ></ylheader>
    <div  class="navigation">
      <ul class="middle_flex">
        <li v-for="(items,index) in titlearray" :key="index" class="middle_flex" @click="changetitleselected(index)"><div class=" title_li_div middle_flex" :class="{title_selected:index==collectionselected}">{{items}}</div></li>
      </ul>
    </div>
    <div class="loadmore-container" ref="collectionWrapper">
      <div class="loadmore-ul">
        <div >
            <div class="shuoshuo-new" v-if="iscollectionempty==true">
              <span class="yl-2kong nosvg">
                  <span class="path1">
                    <span class="path2">
                      <span class="path3">
                        <span class="path4">
                          <span class="path5">
                            <span class="path6">
                              <span class="path7">
                                <span class="path8">
                                  <span class="path9"></span>
                                </span>
                              </span>
                            </span>
                          </span>
                        </span>
                      </span>
                    </span>
                  </span>
              </span>
            <span class="no-text">您还没有收藏内容哦~</span>
          </div>
          <div v-for="(item,index) in list" :key="index">
            <div v-if="item.type==0" class="commonstyle">
                  <searchresulttopic @topicback="totopicdet" :topicimg="item.pictureList[0].src" :abbreviations="item.content" :followNumber="item.likeNum"
                    :title="item.title"  :tabId="0" :topicItem="item" :topicindex="index" ></searchresulttopic>
            </div>
           <div class="hot-shuohsuo" v-else-if="item.type==1">
              <div class="commonstyle">
                <hotheader :commentindex="index" :type="1" :nickname="item.userName" :saytime="item.createTimestamp" :avatarimg="item.headImg"
                          @topiccommentdetail="tosaycomdet" :place="item.place" :tabId="0" :ssshow='item.isRecommend==1' :userType="item.userType" :isTalent="item.isTalent" :pendantType="item.pendantType" :pendantPicUrl="item.pendantPicUrl"></hotheader>
                <commentbody  @showImg="popupImg"  :commentindex="index" :commenttype="null" @replycomment="tosaycomdet" :commenttext="item.content"
                            :piclength="item.pictureList.length"  :picarray="item.pictureList" :tabId="0" ></commentbody>
                <thubm-up :topiccommentnum="item.commentNumber" :thumbupnum="item.likeNum" :commentindex="index" :isup="item.isgood"
                          @thumbup="saythumbup" @commentsvgg="tosaycomdet" :tabId="0"></thubm-up>
              </div>
            </div>
             
            <div class="hot-replace" v-else-if="item.type==2">
              <div class="commonstyle">
                <searchresultreplace  @replycomment="torepcomdet" :tabId="0"  :commentindex="index" :topicimg="item.picture" :abbreviations="item.title"  :title="item.title" :price="item.price"></searchresultreplace>
              </div>
            </div>
          </div>
        </div>
        <p style="height:1rem"></p>
      </div>
    </div>
        <transition name="fade">
      <div class="modal-img" v-if="popupVisible" @click="popupVisible=false">
        <mt-swipe :auto="100000" style="width: 100%;height: 100vh;position:relative;"
        :continuous="false" 
          :defaultIndex="swiperIndex" :showIndicators="false" >
            <mt-swipe-item v-for="(item,index) in popImg" :key="index" style="height:100vh" >
              <img v-lazy="item" class="swiper-img" />
            </mt-swipe-item>
          </mt-swipe>
      </div>
    </transition>
  </div>
</template>
<script>
import ylheader from "src/components/yl-header.vue";
import searchresulttopic from "src/components/seachresult/searchresulttopic.vue";
import searchresultreplace from "src/components/seachresult/searchresultreplace.vue";
import commentbody from "src/components/comment-detail-body.vue";
import hotheader from "src/components/allhot-header.vue";
import thubmUp from "src/components/thumb-up.vue";
import api from "src/api/index";
import { mapState, mapMutations } from "vuex";
export default {
name:"collection",
  data(){
    return{
      swiperIndex:0,
      popupVisible:false,
      popImg:'',
      titlearray:["全部","话题","说说","闲置"],
      page:1,
      totalPage:0,
      type:null,
      iscollectionempty:false,
      list:[],
      is_r:false,
    }
  },
  components:{
    ylheader,
    api,
    commentbody,
    hotheader,
    thubmUp,
    searchresulttopic,
    searchresultreplace,
  },
  computed: {
    ...mapState(["collectionselected"])
  },
  mounted(){
    this.getcollection().then(data=>{
      this.initScroll();
    }).then(data => {
      this.$nextTick(() => {
        if (!!this.myscroll) this.myscroll.refresh();
      });
      let loadmore = document.getElementsByClassName("loadmore-ul");
      if ("collect2detail" == localStorage.turnCount) {
        if (loadmore.length > 0) {
          setTimeout(() => {
            loadmore[0].style.transform = localStorage.turnBackCollection;
          }, 0);
        }
        localStorage.turnCount = "";
      } 
    });
  },
  methods:{
    ...mapMutations(["changecollectionselected"]),
           //显示图片
    popupImg(data,index){
      console.log(data,index)
      this.swiperIndex = index
      if(typeof data == 'string'){
        data = data.split(',')
      }
       //console.log(data,index)
      this.popImg = data;
      this.popupVisible = true;
      // console.log(this.swiperOne)
      // this.swiperOne.slideTo(index)
    },
        //初始化scroll
    initScroll() {
      let p = new Promise((resolve, reject) => {
        this.$nextTick(() => {
          let collectionWrapper = this.$refs.collectionWrapper;
          this.setScroll(collectionWrapper, this);
        });
        resolve("初始化scroll结束...");
      });
      return p;
    },
    setScroll(collectionWrapper, _this) {
      localStorage.tempPageHeight = document.getElementsByClassName(
        "loadmore-ul"
      )[0].scrollHeight;
      _this.myscroll = new iScroll(collectionWrapper, {
        //上拉时触发
        onScrollMove: function() {
          if (
            this.y <= this.wrapperH - this.scroller.clientHeight - 50 &&
            _this.is_r == false
          ) {
            //加载数据
            _this.is_r = true;
            if(_this.page<_this.totalPage){
              _this.page++;
              _this.getcollection();  
            }
          }
        },
        onScrollEnd: function() {},
        onScrollStart: function() {
          if (
            localStorage.tempPageHeight !=
            document.getElementsByClassName("loadmore-ul")[0].scrollHeight
          ) {
            this.refresh();
            localStorage.tempPageHeight = document.getElementsByClassName(
              "loadmore-ul"
            )[0].scrollHeight;
          }
        }
      });
    },
   changetitleselected(index){
      this.is_r=false;
      this.page=1;
      this.changecollectionselected(index);
      if(index==0){
          this.type=null;
      }else{
        this.type=this.collectionselected-1;
      }
      this.getcollection();
      this.myscroll.scrollTo(0,0);
    },
    getcollection(){
        let p = new Promise((resolve, reject) => {
          if ("collect2detail" == localStorage.turnCount) {
          let collectionObj = JSON.parse(localStorage.collectionStorage);
          this.list = collectionObj.list;
          this.page = collectionObj.page;
          this.totalPage = collectionObj.totalPage;
          if(this.page<this.totalPage){
            this.is_r=false;
          }
          resolve(true);
        }else{
          const params = {page:this.page,limit:10,type:this.type};
          api.getCollectionItemList(params).then(res=>{
            if(res.success){
              this.totalPage = res.data.totalPage;
              this.list= this.is_r
                  ? [...this.list, ...res.data.list]
                  : res.data.list;
              if(this.page<=res.data.totalPage){
                this.is_r=false;
              }else{
                this.is_r=true;
              }
             if(this.list.length==0){
                this.iscollectionempty = true;
              } else{
                this.iscollectionempty = false;
              }
              this.picAutoOrient(this.page-1);
              if(this.myscroll){
                this.$nextTick(() => {
                  this.myscroll.refresh();
                });
              }
           
             let collectionObj = JSON.stringify({
               list:this.list,
               page: this.page,
               totalPage: this.totalPage,
             });
             localStorage.collectionStorage = collectionObj;
             resolve("获取推送内容....");
            } 
             resolve("所有结果..."); 
          })
         }
        })
        return p;
    },
    saythumbup(data) {
      this.say = this.list
      const params = {
        saysId: this.say[data.commentindex].id,
        createSaysUserId: this.say[data.commentindex].userId
      };
      if (this.say[data.commentindex].isgood == 0) {
        api.Querysaythumbup(params).then(res => {
          if (res.success) {
            this.say[data.commentindex].isgood = !this.say[data.commentindex]
              .isgood;
            this.say[data.commentindex].likeNum += 1;
          }
        });
      } else if (this.say[data.commentindex].isgood == 1) {
        api.Querysaycanclethumbup(params).then(res => {
          if (res.success) {
            this.say[data.commentindex].isgood = !this.say[data.commentindex]
              .isgood;
            this.say[data.commentindex].likeNum -= 1;
          }
        });
      }
    },
    torepcomdet(data) {
      localStorage.tabCount = data.tabId;
      localStorage.turnCount = "collect2detail";
      this.getTransformState();
      const addclick = {
        id:this.list[data.commentindex].id ,
        type: 3
      };
      this.$util.saveclicknum(addclick);
      this.$router.push({
        path: "/replacedetail",
        query: { replacedId: this.list[data.commentindex].id }
      });
    },
    tosaycomdet(data) {
      localStorage.tabCount = data.tabId;
      localStorage.turnCount = "collect2detail";
      this.getTransformState();
      const addclick = {
        id: this.list[data.commentindex].id,
        type: 2
      };
      this.$util.saveclicknum(addclick);
      this.$router.push({
        path: "/shuodetail",
        query: {
          saysId: this.list[data.commentindex].id,
          userId: this.list[data.commentindex].userId
        }
      });
    },
    totopicdet(items) {
      localStorage.tabCount = items.tabId;
      localStorage.turnCount = "collect2detail";
      this.getTransformState();
      const addclick = {
        id: this.list[items.topicindex].id,
        type: 1
      };
      this.$util.saveclicknum(addclick);
      this.$router.push({
        path: "/topicdetail",
        query: {
          topicId:this.list[items.topicindex].id,
          activeId: items.topicItem.activityId,
          token:localStorage.getItem("token")
        }
      });
    },
    //图片自动旋转参数
    picAutoOrient(data) {
      for (var m = 10 * data; m < this.list.length; m++) {
        if(this.isEmpty(this.list[m].pictureList)==false){
          for (var n = 0; n < this.list[m].pictureList.length; n++) {
            this.list[m].pictureList[n].src =
              this.list[m].pictureList[n].src + "?imageMogr2/auto-orient";
          }
        }
      }
    },
    //空数组
    isEmpty(value){
       return (Array.isArray(value) && value.length === 0) || (Object.prototype.isPrototypeOf(value) && Object.keys(value).length === 0);
    },
      //获取跳转前的位置
    getTransformState() {
      let loadmore = document.getElementsByClassName("loadmore-ul");
      if (loadmore.length > 0) {
        localStorage.turnBackCollection = loadmore[0].style.transform;
      }
    }
  }
}
</script>
<style scoped>

.navigation ul{
  background: #fff;
  height: 0.9rem;
}
.navigation ul li{
  flex: 1;
  font-size: 0.32rem;
  color: #494949;
}
.title_selected{
  width: 1rem;
  border-bottom: 2px solid #fb685b;
  color: #fb685b;
  height: 100%;
}
.title_li_div{
  height: 0.9rem;
  line-height: 0.9rem;
}
.middle_flex{
  display: flex;
  justify-content: center;
  align-self: center;
  flex-direction: row;
}
.commonstyle{
  background-color: white;
  margin-top: 0.2rem
}
</style>
